package com.priox.sigar.infraestructura.persistence.jpa.sigar;

import com.mm.support.jpa.BaseDAO;
import com.priox.sigar.domain.model.ComunRepository;
import com.priox.sigar.server.infrastructure.persistence.util.FormatUtil;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.Iterator;
import java.util.List;


/**
 * User: aglwkrs
 * Date: 30/11/11
 */
@Repository
public class ComunRepositoryImpl extends BaseDAO implements ComunRepository {
    private Long lastSyncTime = null;
    private Long delta = null;



    public Date now() {
        long nowJVM = System.currentTimeMillis();
        int TIMEOUT_REFRESCO = 30 * 60 * 1000;   // jalar fecha si antiguedad > 30 minutos
        long refreshAgeMilis = lastSyncTime == null ? 0 : nowJVM - lastSyncTime;
        if (delta == null || lastSyncTime == null || refreshAgeMilis > TIMEOUT_REFRESCO) {
            synchronized (this) {
                lastSyncTime = nowJVM;
                Date nowBD = (Date) em().createNativeQuery("SELECT current timestamp  as now FROM sysibm.sysdummy1").getSingleResult();
                delta = nowBD.getTime() - nowJVM;
                LOG.debug("BD date " + FormatUtil.formatFull(nowBD) + " deltaMilis:" + delta + " refreshAgeMilis:" + refreshAgeMilis + " refreshAgeTIMEOUTMilis:" + TIMEOUT_REFRESCO);
            }
        }
        Date result = new Date(nowJVM + delta);
        return result;
    }


    public void persistEntity(List entitys){
        for (Iterator iterator = entitys.iterator(); iterator.hasNext(); ) {
            Object next = iterator.next();
            em().persist(next);
        }
    }

}
